//
//  OPReplyPost.m
//  OPFramework
//
//  Created by malcom on 7/22/08.
//  Copyright 2008 malcom-mac software. All rights reserved.
//

#import "OPSendPost.h"
#import "OPBoard.h"
#import "OPBoard_Extensions.h"

@implementation OPSendPost

@synthesize p_includeSignature;
@synthesize p_enableBBCodes;
@synthesize p_enableURLs;
@synthesize p_subject;
@synthesize p_messageText;
@synthesize p_postID;
@synthesize p_enableSmiles;
@synthesize p_password;

- (id) initNewPostWithSubject:(NSString *) _subject message:(NSString *) _message inForum:(OPForum *) _forum {
	self = [super init];
	if (self != nil) {
		_delegateBoard = [_forum._delegateBoard retain];
		
		p_messageText = [_message retain];
		p_subject = [_subject retain];
		p_postID = nil;

		p_forum = _forum._forumID;
		p_topic = -1; // new topic
		
	}
	return self;
}

- (id) initToReplyToTopic:(OPTopic *) _topid quoting:(NSArray *) _quotes fromBoard:(OPBoard *) _board {
	self = [super init];
	if (self != nil) {
		_delegateBoard = [_board retain];
		
		p_messageText = [[NSMutableString alloc] init];
		p_subject = [_topid.p_topicTitle retain];
		p_postID = nil;

		p_forum = _topid.obj_parentForum._forumID;
		p_topic = [_topid.p_topicID intValue]; // a reply to an existing post
		
		[self _generareQuotesFromPosts: _quotes];
	}
	return self;
}

- (void) _generareQuotesFromPosts:(NSArray *) _quotes {
	for (OPPost *cPost in _quotes) {
		NSString *quotedText = [NSString stringWithFormat: @"[quote=\"%@\"]%@[/quote]",cPost.p_author.p_username,cPost.p_message];
		[p_messageText appendFormat: @"%@\n",quotedText];
	}
}

- (NSString *) description {
	return [NSString stringWithFormat: @"OPReplyPost: (%@) subject: %@, message length: %d",(p_postID == nil ? @"not sent" : @"sent"),
																			p_subject,[p_messageText length]];
}

- (NSNumber *) sendMessageWithPassword:(NSString *) _password {
	if (p_postID != nil) return p_postID; // yet sent
	
	[p_password release]; p_password = [_password retain];
	
	if (p_topic > -1) { // it's a reply
		NSArray *_params = [NSArray arrayWithObjects:	p_subject,
													p_messageText, 
													[NSNumber numberWithInt: p_forum],
													[NSNumber numberWithInt: p_topic],
													(_password == nil ? @"" : _password),
													[NSNumber numberWithBool: p_enableBBCodes],
													[NSNumber numberWithBool: p_enableSmiles],
													[NSNumber numberWithBool: p_enableURLs],
													[NSNumber numberWithBool: p_includeSignature],
													(_password != nil ? _password : @""),nil];
		[self sendXMLRequestForMethod: @"msg_sending.replyToPost" withParams:_params parseSelector: @selector(_parseSendResult:) forceSyncRequest: YES];
	} else { // it's a new post 
		NSArray *_params = [NSArray arrayWithObjects:	p_subject,
														p_messageText, 
														[NSNumber numberWithInt: p_forum],
														[NSNumber numberWithBool: p_enableBBCodes],
														[NSNumber numberWithBool: p_enableSmiles],
														[NSNumber numberWithBool: p_enableURLs],
														[NSNumber numberWithBool: p_includeSignature],(_password == nil ? @"" : _password) ,nil];

		[self sendXMLRequestForMethod: @"msg_sending.postNewTopic" withParams:_params parseSelector: @selector(_parseSendResult:) forceSyncRequest: YES];
	}
	return p_postID;
}




- (void)connection: (XMLRPCConnection *)connection didReceiveResponse:(XMLRPCResponse *)response forMethod: (NSString *)method {
	// super class check if it's an error, a numeric response or simply some data to parse
	if (![self _checkErrorInRawResponseFromServer: response forMethod:method]) {
		// data update to parse
		[self _parseSendResult: [NSArray arrayWithObjects: [response responseObject],method,nil]];
		// we can propagate the result to listeners
		[self dataUpdatedFor: self atMethod:method];	
	}
}

- (BOOL) _isNumericResponseFromServerAnErrorCode:(NSNumber *) _code forMethod:(NSString *) method {
	BOOL isErrr = NO;
	switch ([_code intValue]) {
		case OFAPI_SUBMIT_INVALID_MODE:
		case OFAPI_NO_POST_MODE:
		case OFAPI_PROTECTED_FORUM_NEED_PASSWORD:
		case OFAPI_BOT_GO_HOME:
		case OFAPI_USER_CANNOT_READ:
		case OFAPI_USER_CANNOT_POST:
		case OFAPI_TOPIC_LOCKED:
		case OFAPI_NOT_AUTHORISED:
			isErrr = YES;
			break;
	}
	
	if (isErrr) { [p_postID release]; p_postID = nil; _lastErrorCode = [_code intValue]; }
	return NO;
}

- (void) _parseSendResult:(NSArray *) _result {
	[p_postID release];
	p_postID = [[[_result objectAtIndex: 0] objectForKey: @"post_id"] retain];
	
}
				
- (OPTopic *) getParentTopic {
	if (p_topic == -1) { // this a new sent topic, we can generate a new sparse OPTopic object loading properties
		return [[OPTopic alloc] initLoadingTopicWithID: [NSNumber numberWithInt: p_topic] 
											 fromForum: [_delegateBoard.obj_boardStructure getForumFromID: [NSNumber numberWithInt: p_forum]]
											  password: p_password
											 forceLoad: YES];
	} else {
		// otherwise it will refresh the cache for post's page
		OPTopic *topic = [[_delegateBoard.obj_boardStructure getForumFromID: [NSNumber numberWithInt: p_forum]] getCachedTopicWithID: [NSNumber numberWithInt: p_topic]];
		[topic getPostsInPage: [self getPostPageIndexInTopic]];
		return topic;
	}
}

- (int) getPostPageIndexInTopic {
	if (p_postID != nil) return [_delegateBoard getPostPageIdxOf: p_postID inTopic: [NSNumber numberWithInt: p_topic] ofForum: [NSNumber numberWithInt: p_forum]];
	else return -1;
}

		
@end
